package com.wsoft.core.filter;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * 功能描述
 *
 * @author: juiet
 * @date: 2024年08月24日 15:44
 */
@Component
public class LocaleFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求中的语言参数
        String language = request.getHeader("Accept-Language");
        Locale locale;
        if (StringUtils.hasText(language)) {
            // 如果请求头中携带了国际化的参数，创建对应的 Locale 对象
            locale = new Locale(language);
        } else {
            //如果没有，使用默认的 Locale 对象（根据主机的语言环境生成一个 Locale ）。
            locale = Locale.getDefault();
        }
        LocaleContextHolder.setLocale(locale);
        filterChain.doFilter(request, response);
    }
}
